package com.photoeditor.demo.ui.widget.sticker;

import android.content.Context;
import android.support.constraint.ConstraintLayout;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import com.common.base.utils.DeviceUtils;
import com.common.base.utils.thread.ThreadPool;
import com.photoeditor.R;
import com.photoeditor.demo.model.event.FilterDownloadBtnClickEvent;
import com.photoeditor.demo.model.store.download.DownloadUtils;
import com.photoeditor.demo.model.store.download.IDownloadListener;
import com.photoeditor.demo.model.store.module.BaseOnlineManager;
import com.photoeditor.demo.model.store.module.StoreOnlineBean;
import com.photoeditor.demo.model.store.module.StoreOnlineManager;
import com.photoeditor.demo.ui.widget.CircleTextProgressbar;

import org.greenrobot.eventbus.EventBus;

import java.lang.ref.WeakReference;

/**
 * Created by Lai on 2019/7/8 0008.
 */
public class StickerPanelDownloadView extends ConstraintLayout implements View.OnClickListener, View.OnTouchListener {

    private StoreOnlineBean mStoreOnlineBean;
    private int mResType;
    private boolean mForceGone;

    private IDownloadListener mDownloadListener;
    private View mButton;
    private CircleTextProgressbar mProgressbar;

    public StickerPanelDownloadView(Context context) {
        super(context);
    }

    public StickerPanelDownloadView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public StickerPanelDownloadView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        mButton = findViewById(R.id.btn_sticker_download);
        mProgressbar = findViewById(R.id.progress_view);
        mButton.setOnClickListener(this);
    }

    public void setData(String pkgName, int resType, boolean forceGone) {
        mResType = resType;
        mForceGone = forceGone;
        if (mResType == BaseOnlineManager.STORE_FUNC_TYPE_STICKER) {
            mStoreOnlineBean = StoreOnlineManager.getInstance().getStickerItemBeanByPackageName(pkgName);
            mProgressbar.setProgressLineWidth(DeviceUtils.dip2px(4));
            setOnTouchListener(this);
        } else if (mResType == BaseOnlineManager.STORE_FUNC_TYPE_FILTER) {
            mStoreOnlineBean = StoreOnlineManager.getInstance().getFilterItemBeanByPackageName(pkgName);
            setOnTouchListener(null);
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        setVisibility(VISIBLE);
        initStatus();
    }

    private void initStatus() {
        if (mForceGone) {
            updateProgress(100);
            return;
        }
        if (mStoreOnlineBean != null) {
            String packageName = mStoreOnlineBean.getPkgName();
            if (mDownloadListener == null) {
                mDownloadListener = new DownloadListener(packageName, this);
            } else {
                DownloadUtils.getInstance().removeListener(mDownloadListener);
                mDownloadListener = new DownloadListener(packageName, this);
            }
            DownloadUtils.getInstance().addListener(mDownloadListener);
            if (BaseOnlineManager.isInstalledByPkgName(packageName)) {
                updateProgress(100);
            } else if (DownloadUtils.getInstance().getDownloadStatus(packageName) == DownloadUtils.DOWNLOAD_DEFAULT) {
                updateProgress(-1);
            } else {
                int percentage = DownloadUtils.getInstance().getPercentage(packageName);
                updateProgress(percentage);
            }
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        DownloadUtils.getInstance().removeListener(mDownloadListener);
    }

    public void updateProgress(int percentage) {
        mProgressbar.setProgress(percentage);
        if (percentage < 0) {
            // 未下载状态
            mButton.setVisibility(VISIBLE);
            mProgressbar.setVisibility(GONE);
        } else if (percentage == 0) {
            // 开始下载初始化
            mButton.setVisibility(GONE);
            mProgressbar.setVisibility(VISIBLE);
        } else if (percentage < 100) {
            // 下载中
            mButton.setVisibility(GONE);
            mProgressbar.setVisibility(VISIBLE);
        } else {
            setVisibility(GONE);
        }
    }

    private static class DownloadListener implements IDownloadListener {
        private String mDownloadId;
        private WeakReference<StickerPanelDownloadView> mRef;

        public DownloadListener(String downloadId, StickerPanelDownloadView view) {
            mDownloadId = downloadId;
            mRef = new WeakReference<>(view);
        }

        @Override
        public String getDownloadId() {
            return mDownloadId;
        }

        @Override
        public void onProgressUpdate(final String downloadId, final int progress) {
            if (!TextUtils.isEmpty(downloadId) && mDownloadId.equals(downloadId)) {
                if (mRef != null && mRef.get() != null) {
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
                            if (mRef.get() != null) {
                                mRef.get().updateProgress(progress);
                            }
                        }
                    });
                }
            }
        }

        @Override
        public void onFailed(final String downloadId) {
            if (!TextUtils.isEmpty(downloadId) && mDownloadId.equals(downloadId)) {
                if (mRef != null && mRef.get() != null) {
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
                            if (mRef.get() != null) {
                                Toast.makeText(mRef.get().getContext(),
                                        mRef.get().getContext().getResources().getString(R.string.filter_download_failed), Toast.LENGTH_SHORT).show();
                                mRef.get().updateProgress(-1);
                            }
                        }
                    });
                }
            }
        }

        @Override
        public String getFullActivityName() {
            return "";
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_sticker_download) {
            if (mStoreOnlineBean != null) {
                DownloadUtils.getInstance().startDownload(mStoreOnlineBean, mResType);
                if (mResType == BaseOnlineManager.STORE_FUNC_TYPE_FILTER) {
                    EventBus.getDefault().post(new FilterDownloadBtnClickEvent(mStoreOnlineBean.getPkgName()));
                }
            }
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return true;
    }
}
